package com.todo.message.application.core.receiver.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.todo.common.utils.DateUtils;
import com.todo.message.application.core.pending.Task;
import com.todo.message.application.core.pending.TaskPendingHolder;
import com.todo.message.application.core.receiver.service.ConsumeService;
import com.todo.message.application.handler.operation.HandlerHolder;
import com.todo.message.infrastructure.entity.domain.RecallTaskInfo;
import com.todo.message.infrastructure.entity.domain.TaskInfo;
import com.todo.message.infrastructure.util.GroupIdMappingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 3y
 */
@Slf4j
@Service
public class ConsumeServiceImpl implements ConsumeService {

    @Autowired
    private ApplicationContext context;

    @Autowired
    private TaskPendingHolder taskPendingHolder;

    @Autowired
    private HandlerHolder handlerHolder;

    @Override
    public void consume2Send(List<TaskInfo> taskInfoLists) {
        String topicGroupId = GroupIdMappingUtils.getGroupIdByTaskInfo(CollUtil.getFirst(taskInfoLists.iterator()));
        for (TaskInfo taskInfo : taskInfoLists) {
            log.info("ConsumeService#consume2Send log print currentTime：【{}】, recallTaskInfo:【{}】", DateUtils.getTime(), JSONObject.toJSONString(taskInfo));

            Task task = context.getBean(Task.class).setTaskInfo(taskInfo);
            taskPendingHolder.route(topicGroupId).execute(task);
        }
    }

    @Override
    public void consume2recall(RecallTaskInfo recallTaskInfo) {
        log.info("ConsumeService#consume2recall log print currentTime：【{}】, recallTaskInfo:【{}】", DateUtils.getTime(), JSONObject.toJSONString(recallTaskInfo));
        handlerHolder.route(recallTaskInfo.getSendChannel()).recall(recallTaskInfo);
    }
}
